###################################################################
############### Data mining: Apriori in R
##Itemset. - A collection of one or more items. 
##. Example: {Milk, Bread, Diaper}
##  a set of items that appears in many baskets is said to be "frequent."

library(arules)
library(arulesViz)
library(datasets)

data("Groceries")
class(Groceries)

inspect(head(Groceries, 5))
#or
inspect(Groceries[1:5])

size(head(Groceries))

itemFrequencyPlot(Groceries, topN=10, type="absolute", main="Item Frequency") # plot frequent items


## we apply the arules apriori algorithm 
##generated. We consider rules for items with minimum support of .0001,
##generating a combo with confidence  of at least .8. 
#The output of the algorithm are the association rules together with the confidence 

groceryrules = apriori (Groceries, parameter = list(supp = 0.001, 
                                                    conf = 0.8)) # Min Support as 0.001, confidence as 0.8.

rules_conf = sort (groceryrules, by="confidence", decreasing=TRUE) 
# 'high-confidence' rules.

inspect(head(rules_conf)) # show the support, lift and confidence for all rules

#rules by lift-->actor by which, the co-occurence of A and B exceeds the 
#expected probability of A and B co-occuring, 
#had they been independent. 
#So, higher the lift, higher the chance of A and B occurring together

rules_lift = sort (groceryrules, by="lift", decreasing=TRUE) # 'high-lift' rules.
inspect(head(rules_lift)) # show the support, lift and confidence for all rules


## rules related to a given item- rice

rules = apriori (data=Groceries, 
                  parameter=list (supp=0.001,conf = 0.08), 
                  appearance = list (default="lhs",rhs="rice"), 
                  control = list (verbose=F)) 


# get rules that lead to buying 'rice'

rules_conf = sort (rules, by="confidence", decreasing=TRUE) # 'high-confidence' rules.
inspect(head(rules_conf))

## The is a case to find out the Customers who bought 'rice' also bought . .

rules = apriori (data=Groceries, 
                 parameter=list (supp=0.001,conf = 0.20,minlen=2), 
                 appearance = list(default="rhs",lhs="rice"), 
                 control = list (verbose=F)) 
# those who bought 'ruce' also bought..
rules_conf = sort (rules, by="confidence", decreasing=TRUE) # 'high-confidence' rules.
inspect(head(rules_conf))